<?php

namespace App\Console\Commands;

use App\Models\DormitoryRating;
use App\Models\DormRatingMain;
use Illuminate\Console\Command;

class GenDormRatingMajor extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'gen:dorm-rating-major {--p|period_id=} {--d|dorm_id=null}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate dorm rating major';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $period_id = $this->option('period_id');
        $dorm_id = $this->option('dorm_id');
        $this->info("Generating dorm rating major for period $period_id and dorm $dorm_id");
        if ($dorm_id == 'null') {
            $dormRatings = DormitoryRating::query()->where('period_id', $period_id)->get();
        } else {
            $dormRatings = DormitoryRating::query()->where('period_id', $period_id)->where('dorm_id', $dorm_id)->get();
        }
        $dormGroups = $dormRatings->groupBy('dorm_id');
        foreach ($dormGroups as $dorm_id => $dormRatings) {
            $this->info("Generating dorm rating major for dorm $dorm_id");
            $remark = $dormRatings->implode('remark', ', ');
            $this->info("Remark: $remark");
            DormRatingMain::query()->updateOrCreate(
                ['dorm_id' => $dorm_id, 'period_id' => $period_id],
                [
                    'dorm_id' => $dorm_id,
                    'period_id' => $period_id,
                    'get_score' => $dormRatings->sum('score'),
                    'total_score' => $dormRatings->sum('subitem_score'),
                    //'score_rate' => $totalScore > 0 ? $getScore / $totalScore * 100 : 0,
                    'remark' => $remark,
                ]
            );
        }
    }
}
